package com.itheima.反射.反射获取构造方法对象;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

/**
 * @Author 王加鑫
 * @Date 2021/5/26 11:32
 * @Version 1.0
 */
public class Demo01 {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        //method1();

        //method2();

        method3();

        method4();

    }

    private static void method4() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<Stu> stuClass = Stu.class;
        //获取指定的任意修饰符修饰的构造方法
        Constructor<Stu> declaredConstructor = stuClass.getDeclaredConstructor(String.class);
        declaredConstructor.setAccessible(true);
        Stu stu = declaredConstructor.newInstance("张三");
        System.out.println(stu);
    }

    private static void method3() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<Stu> stuClass = Stu.class;
        //获取指定的public修饰的构造方法
        Constructor<Stu> constructor = stuClass.getConstructor(String.class, int.class);
        Stu stu = constructor.newInstance("张三", 23);

        System.out.println(stu);
    }

    private static Class<Stu> method2() {
        Class<Stu> stuClass = Stu.class;

        //获取当前类所有的构造方法
        Constructor<?>[] declaredConstructors = stuClass.getDeclaredConstructors();
        System.out.println(Arrays.toString(declaredConstructors));
        return stuClass;
    }

    private static Class<Stu> method1() {
        Class<Stu> stuClass = Stu.class;

        //获取所有public修饰的构造方法
        Constructor<?>[] constructors = stuClass.getConstructors();
        System.out.println(Arrays.toString(constructors));
        return stuClass;
    }
}
